<?php                                           
chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";

class phone_orders extends IPlugin {
    var $color;

    function phone_orders($parent = null) {
        IPlugin :: IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
        $this->color = "red";
    }

    function getPluginTag() {
        return "phone_orders";
    }
    function getPluginName() {
        return "phone_orders Plugin";
    }
    function getPluginVersion() {
        return "1.0.0";
    }

    function getProperty($p = null) {
        if (null == $p) {
            return array ("MenuTitle", "MenuBlockTitle");
        }
        $result = "";
        switch ($p) {
            case "MenuBlockTitle" :
                {return "Phone Order System";}
                break;
            case "MenuTitle" :
                {return "Purchasing";}
                break;
        };
        return $result;
    }

    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------

    function doAction($params) {
        $core = getCoreInstance();
        $db = $core->getProperty("db");
        //$render = $core->framework->smarty;
        if (null != ($result = IPlugin :: doAction($params))) {
            return $result;
        }
        $arg = getCoreInstance();
        $arg = $arg->getGET();
        //unset($_SESSION[cart]);
        
        switch ($_GET["action"]) {
            
            case "add" :
                $p=0;
                for ($i=0; $i<count($_SESSION[cart]); $i++)
                {
                    if ($_SESSION[cart][$i][id]==$_GET[id]) 
                    {
                        $_SESSION[cart][$i][qty]+=$_POST[qty];
                        $p=1;
                    }
                }
                if (!$p) $_SESSION[cart][]=array("id" => $_GET[id], "qty" => $_POST[qty]);
            break;
            
            case "recalculate" :
                    $i=0;
                 foreach ($_POST[qty] as $k => $v)
                 {
                    $_SESSION[cart][$i][qty]=$v;
                    $i++;
                 }
            break;

            case "clear" :
                unset($_SESSION[cart]);
            break;

            case "delete" :
                $new_cart=array();
                for ($i=0; $i<count($_SESSION[cart]); $i++)
                {
                    if ($_SESSION[cart][$i][id]!=$_GET[id]) $new_cart[]=$_SESSION[cart][$i];
                }
                $_SESSION[cart]=$new_cart;
            break;
            
            case "checkout" :
                 $error=0;
                 if ($_POST[client]=="new") 
                    if (0 < $db->getone("select count(*) from clients where client_name='$_POST[c_name]'")) {$error=1;$_SESSION[error]="Error: Client with such name already exists";}
                    elseif (0 < $db->getone("select count(*) from clients where client_email='$_POST[c_email]'")) {$error=1;$_SESSION[error]="Error: Client with such email already exists";}
                if (!$error)
                {
                ////..........................................................................................  
                    if ($_POST[client]=="exists")
                    {
                        $_P=$db->getrow("select client_ccexpdate, client_cctype as cctype, client_ccnumber as ccnumber, client_ccholdername as ccholdername, client_cccvv as cccvv, 
                                        client_name as c_name, client_email as c_email, client_phone as c_phone, client_billing_adress1 as c_address, client_billing_city as c_city, client_billing_state, client_billing_country, 
                                        client_billing_zip as c_zip, client_shipping_adress1 as c_shipping_address, client_shipping_city as c_shipping_city, client_shipping_state,
                                        client_shipping_zip as c_shipping_zip, client_shipping_country
                                       from clients where client_id=$_POST[client_id]");
                         $_P[total] = $_POST[total];
                         $client_id=$_POST[client_id];
                    } 
                    else 
                    {
                        //=======-------------------   [  REGISTER CLIENT
                        $_POST_DB=arraystr2db($_POST);
                        $client_id=$db->exec("insert into clients 
                        (client_name,client_password,client_email,client_phone,client_billing_city,client_billing_state,client_billing_country,client_billing_adress1,client_billing_zip,
                            client_cctype,client_ccnumber,client_ccexpdate,client_ccholdername,client_cccvv,
                                client_shipping_adress1,client_shipping_city,client_shipping_state,client_shipping_zip,client_shipping_country) 
                                values ('$_POST_DB[c_name]','".md5($_POST_DB[c_name])."','$_POST_DB[c_email]','$_POST_DB[c_phone]','$_POST_DB[c_city]','$_POST_DB[client_billing_state]','$_POST_DB[client_billing_country]',
                                        '$_POST_DB[c_address]','$_POST_DB[c_zip]','$_POST_DB[cctype]','$_POST_DB[ccnumber]','".$_POST_DB[expdateMonth].substr($_POST_DB[expdateYear],-2)."','$_POST_DB[ccholdername]','$_POST_DB[cccvv]',
                                        '$_POST_DB[c_shipping_address]','$_POST_DB[c_shipping_city]','$_POST_DB[client_shipping_state]','$_POST_DB[c_shipping_zip]','$_POST_DB[client_shipping_country]')");
                        //=======-------------------   REGISTER CLIENT ]
                        $_P=$_POST;
                    }
                    $db->Exec("insert into orders(ccexpdate,cctype, ccnumber, ccholdername, cccvv, pubdate, fname, lname, company, address1, address2, city, state, zip, country, email, phone,
                                        findus, findother,
                                        sfname, slname, saddress1, saddress2, scity, sstate, szip, scountry,
                                        price, status, shipment,discount,code_confirmation)
                                values( ?, ?, ?, ?, ?, now(),
                                        ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
                                        ?, ?,
                                        ?, ?, ?, ?, ?, ?, ?, ?,
                                        ?, ?, ?, ?,?)", 0, array(
                        array($_P[expdateMonth].substr($_P[expdateYear],-2), $_P[cctype], $_P[ccnumber], $_P[ccholdername], $_P[cccvv], $_P[c_name], '', '', $_P[c_address], '', $_P[c_city],
                                        $_P["client_billing_state"], $_P["c_zip"], $_P["client_billing_country"], $_P["c_email"], $_P["c_phone"],
                                '', '',
                                $_P[c_name], '', $_P[c_shipping_address], '', $_P[c_shipping_city], $_P[client_shipping_state],
                                $_P[c_shipping_zip], $_P[client_shipping_country],
                                $_P[total], 1, $_P['shipment'], $_SESSION['secure']['total_discount'],'Y'
                              )
                        ));
                    
                    $id = $db->getInsertID();
                    
                    //inserting into client_orders
                    $sql = "insert into clients_orders (cl_id,order_id) values('$client_id','$id')"; 
                    
                    foreach ($_SESSION[cart] as $v)
                    {
                    
                        $rows=arraydb2str($db->getrow("select our_price as price, title, img_small as thumbnail from catalog where catalog_id=$v[id]"));
                        $db->Exec("insert into purchaseitems(order_id, catalogid, price, qty, title, image) 
                                    values($id, $v[id], $rows[price], $v[qty], '$rows[title]', '$rows[thumbnail]')");
                // --------<START> | Added by Gendich | "qty log on store & mail alert" ---------------------------------                    
                                    /*$db->Exec("insert into store_history (catalog_id,date,action,qty) values ($v[id],now(),'sell',-$v[qty])");
                                    
                                    $qty=$db->getone("select sum(qty) from store_history where catalog_id=$v[id]");
                                    $min_qty=$db->getone("select s_value from settings where s_key='min_qty'");
                                    $was_alert=$db->getone("select min_qty_alert from catalog where catalog_id=$v[id]");
                                    if ($qty<=$min_qty && !$was_alert)
                                    {
                                        $admin_mail=$db->getone("select s_value from settings where s_key='Administrator email'");
                                        $site = $core->config["system"]["www_name"];
                                        $now = date("Y-m-d H:i:s");   
                                            $msg = "
                                                <html>
                                                <body>
                                                    <b> Automatic system of the notification of the <font color=\"blue\">$site</font> informing you:</b> <br />
                                                    <b> </b>  <br />
                                                    Now: $now <br />
                                                    On this time minimum quantity of the goods in a warehouse (STORE) is achieved.<br /> 
                                                        Accept the appropriate measures, please ! <br /><br />
                                                            Minimum qnt = $min_qty; <br />
                                                            The rest = $qty. <br />
                                                    $message_status[$id_status] <br /> <br />
                                                <body>
                                                </html>";
                                            $mail = $core->getSnippet("email");
                                            $m_from=$core->config["system"]["mail_info"];
                                            $m_to=$admin_mail;
                                            $params = array(
                                                "to" => $m_to,
                                                "from" => $m_from,
                                                "body" => $msg,
                                                "subject" => "$site info",
                                                "html" => "1",  // 1/0                              
                                                            );
                                        $mm=$mail->doAction($params);
                                        $db->exec("update catalog set min_qty_alert=1 where catalog_id=$v[id]");
                                    }
                    */}
                // --------<END> | Added by Gendich | ---------------------------------
                    
                // --------[  MAIL---------------------------------
                
                    $rows = "<table cellpadding=2 cellspacing=2 border=0>
                                <tr>
                                    <td colspan=4 align=left >Your cart:</td>
                                </tr>
                                <tr>
                                    <th align=\"left\"><b>Item</b></th>
                                    <th align=\"left\"><b>Price</b></th>
                                    <th align=\"left\"><b>Qty</b></th>
                                    <th align=\"left\"><b>Sub-total</b></th>
                                </tr>
                                ";
                                foreach ($_SESSION[cart] as $v)
                                {
                                    $get_client=$db->getrow("select title, our_price as price from catalog where catalog_id=$v[id]");
                                    $rows .= ($rows=="" ? "" : "<br />\n").
                                            "<tr>
                                                <td>{$get_client[title]}</td>
                                                <td>\$ ".number_format($get_client[price], 2, '.', ' ')."</td>
                                                <td>{$v[qty]}</td>
                                                <td>\$ ".(number_format($v["qty"]*$get_client["price"], 2, '.', ' '))."</td>
                                            </tr>
                                            ";
                                }
                            
                            $rows .= "\n<tr>
                                    <td colspan=2>&nbsp;</td>
                                    <td colspan=2 align=center>Total price: \$ ".number_format($_P[total], 2, '.', ' ')."</td>
                                </tr>\n<table>\n\n";
                    
                        $logoname  = $core->config['system']['logo_name'];
                        $csemail   = $core->config['system']['cust_service'];
                        $csphone   = $core->config['system']['customer_service_number'];
                        $salemail  = $core->config['system']['sales_mail'];
                        $infoemail = $core->config['system']['info_email'];
                        $www_name  = $core->config['system']['www_name'];
                        $info_mail = $core->config['system']['mail_info'];
                        
                    $message = "<html><body>\n<h1>Congratulation!</h1>\n
                    <br />
                    <br />
                    <center> Hello $_P[c_name] </center><br />
                    Thank you for your order<br />
                    Thanks for shopping at $logoname.com This email is confirmation that we have received your order.<br />
                    You will receive another email when the order has shipped.<br />
                    <p>Your order number is <b>$id</b>.</p> 
                          
                    If you will have any questions or comments for us please send an email to <a href=\"mailto:$csemail\">$csemail</a>.<br />
                    Representatives are available 7 days aweek, 9am- 5:00pm EST.<br />
                    
                    Thank you for shopping at $logoname.com <br />
                    
                    $logoname's Customer Service<br />
            
                    $csphone <br />
                    <a href=\"mailto:$csemail\">$csemail</a><br />
                    <a href=\"$www_name\">$www_name</a><br />
                    <hr>
                    <br />
                    Order N $id <br />
                    Items shipped to : <br />
                   
                    <b>Name</b>: {$_P[c_name]}<br>
                    <b>Address</b>: {$_P[c_address]}<br>
                    <b>City</b>: {$_P[c_city]}<br>
                    <b>State</b>: {$_P[client_billing_state]}<br>
                    <b>Zip</b>: {$_P[c_zip]}<br>
                    <b>Country</b>: {$_P[client_billing_country]}<br>
                    <b>Phone</b>: {$_P[c_phone]}<br>
                    <b>Email</b>: {$_P[c_email]}<br>
                    <br />
                    <br />
                    <b>Shipping information:</b><br />
                    <b>Address</b>: {$_P[c_shipping_address]}<br>
                    <b>City</b>: {$_P[c_shipping_city]}<br>
                    <b>State</b>: {$_P[client_shipping_state]}<br>
                    <b>Zip</b>: {$_P[c_shipping_zip]}<br>
                    <b>Country</b>: {$_P[client_shipping_country]}<br>
                    
                    Cart details:<br />
                    {$rows}
                    <br />
                    <hr>
                            
                    <br />
                    Thanks!<br />
                    <br />
                    Sincerely yours,<br />
                    $logoname.com<br />
                    <br /><br />
                    <br />
                    </body>
                    </html>\n\n\n
                    ";
                    $headers  = "MIME-Version: 1.0\r\n"; 
                    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; 
                    $headers .= "From: $logoname store <sales@mbr.com>\r\n"; 
                    $headers .= "Cc: $salemail\r\n"; 
                    //$headers .= "Bcc: $salemail\r\n"; 
                    $today = getdate();
    
                    #@mail("$_P[c_email]", "Order ( ".date("F j, Y, g:i a")." ) #".$id." $logoname", $message, $headers);
                    #@mail("$infoemail", "Order # {$id} $logoname", $message, $headers);

                // --------]  MAIL--------------------------------- 
                    
                unset($_SESSION[cart]); 
                $_SESSION[ok]="Order was successful complete";
                    
                }
                    
                ////..........................................................................................  
                    
                
            break;

        }
        
    }

    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function Render($params) {
        global $_G;
        if (null != ($result = IPlugin :: Render($params))) {
            return $result;
        }

        $core = getCoreInstance();
        $render = $core->framework->smarty;
        $render->assign("baseurl", "?".$this->getURL()."&page=".$_G["page"]);

        $page = "";

        switch ($_G["page"]) {

            case "store_history" :
                $page = $this->renderStoreHistory($render);
                break;                
            default :
                $page = $this->main_render($render);
                break;
        }

        return $render->fetch("file:".$this->tplfolder."/".$page);
    }

    // ----------------------------------------------------------------------------------
    // --- [ Generate CProduct List ] --------------------------------------------------
    // ----------------------------------------------------------------------------------

    function cb_renderCT($data) {
        $catalog_id = $_REQUEST['catalog_id'];

        if (isne($catalog_id)) {
            if ($catalog_id < 0 || !is_numeric($catalog_id)) {
//              header("location: ./?".$this->getURL());
//              exit ();
            }
        } else {
            $catalog_id = 0;
        }
        $parent_id = "";
        if (isne($_REQUEST['parent_id']))
            $parent_id = $_REQUEST['parent_id'];

        $st_paginator_page = $_REQUEST['st_paginator_page'];
        $st_paginator_ppv = $_REQUEST['st_paginator_ppv'];

        $img_small = $data["img_small"];
        $core = & getCoreInstance();
        if (file_exists($core->config["file_root"]."/inventory/".$img_small) && is_file($core->config["file_root"]."/inventory/".$img_small)) 
        {
            $img_small = "<img src='".$core->config["http_root"]."/inventory/{$img_small}' border=0 height=80/>";
        } else {
            $img_small = "No Image";
        }
        // "header" => array ("ID", "IMG", "Title", "Price", "Qty", "Action"), 
        $dt = array (
            array ($data["catalog_id"], "align=\"center\""), 
            array ($img_small, ""), 
            array ($data["title"], ""), 
            array ("$".number_format($data["our_price"], 2, '.', ' '), "align=\"right\""), 
            array ("<form method=\"POST\" action=\"?path=phone_orders&action=add&parent_id={$parent_id}&id={$data[catalog_id]}&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv."\" name=\"fselect$data[catalog_id]\" ><input type=\"text\" name=\"qty\" size=\"10\" ></form>", ""), 
            array ("<a href=\"#select\" onclick=\"if (document.forms['fselect$data[catalog_id]'].elements['qty'].value=='') alert('Enter valid qty please !'); else document.forms['fselect$data[catalog_id]'].submit();\">select</a>", "align=\"center\""));
        return $dt;
    }

    function main_render(& $render) {
        $core = & getCoreInstance();
        $db = $core->getProperty("db");

        $hs = & $core->getSnippet("historylinks");
        if (isne($_GET['parent_id'])) {
            $curent_catalog_id = $_GET['parent_id'];

        }
        elseif (isne($_POST['parent_id'])) {
            $curent_catalog_id = $_POST['parent_id'];
        } else {
            $curent_catalog_id = 0;
        }
        $sb = & $core->getSnippet("sibling");
        $sibling_params = array ("action" => "removeWrongSibling", "table" => "catalog", "sField" => "sibling", // ordering field
        "sId" => "catalog_id", "sParentId" => "parent_id", "sWhere" => "is_category != 'Y'", "sOrderBy" => " order by title",);
        $sb->doAction($sibling_params); // remove sibling = -1

        // ===== end of  sibling = -1*/
            $params = array ("startfrom" => $curent_catalog_id, "f_id" => "catalog_id", "f_parent" => "parent_id", "f_title" => "title", "table" => "catalog", "stopval" => 0, // root
        "url" => "?".$this->getURL()."&catalog_id=###", // ### will be replaced by id
        "html_root" => "Root", "html_url" => "?".$this->getURL(), "html_separatop" => " :: ",);
        $HTML1 = $hs->Render($params);
        $render->assign("catalog_hs", $HTML1."<br/>");

        $pg = & $core->getSnippet("paginator");
        $tmp_url = $this->getURL()."&parent_id=".$curent_catalog_id;
        //      $tmp_url = $this->getURL()."&catalog_id=".$_REQUEST['catalog_id'];
        $page = $ppg = -1; /// curent count page
        $params = array (
            "cb_class" => & $this, 
            "cb_func" => cb_renderCT, 
            "urlbase" => $tmp_url, 
            //"caption" => "Products list", 
            "emptymsg" => "No products collected yet", 
            "header" => array ("ID", "IMG", "Title", "Price", "Qty", "Action"), 
            "items" => "", "source" => "sql", // -- sql, array
            "sql_items" => "select catalog_id, title,our_price,img_small from catalog where is_category != 'Y'  and is_active = 'Y' and parent_id='".$curent_catalog_id."' order by sibling", "sql_count" => "select count(*) from catalog where is_category != 'Y' and is_active = 'Y' and parent_id='".$curent_catalog_id."'", 
            "ippg" => 5, // -- items per page
            "nppv" => 5, // -- number pages per view
            "page" => & $page, "ppg" => & $ppg,);
        $HTML = $pg->Render($params);
        $render->assign("productlist", $HTML);

        getAllHistory(null, "", $res);
        $render->assign("folder_locations", $res);

        $st_paginator_page = $_REQUEST['st_paginator_page'];
        $st_paginator_ppv = $_REQUEST['st_paginator_ppv'];

        $render->assign("add_url", "?".$this->getURL()."&parent_id=".$curent_catalog_id."&page=add&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv);
        $render->assign("url_location", "?".$this->getURL());
        $render->assign("cur_catalog", $curent_catalog_id);

        $render->assign('action_url', "?".$this->getURL()."&parent_id=".$curent_catalog_id);
        
        $render->assign("check_valid", "?".$this->getURL()."&page=checkvalid");
        
        ////// -------- CART ----------------------------
        
        if ($_SESSION[cart]!="")
        foreach ($_SESSION[cart] as $v)
        {
            $rows=$db->getrow("select catalog_id, parent_id, title,our_price,img_small from catalog where catalog_id=$v[id]");
            $img_small = $rows["img_small"];   // check img !
                $core = & getCoreInstance();
                if (file_exists($core->config["file_root"]."/inventory/".$img_small) && is_file($core->config["file_root"]."/inventory/".$img_small)) 
                {
                    $img_small = "<img src='".$core->config["http_root"]."/inventory/{$img_small}' border=0 height=80/>";
                } else {
                    $img_small = "No Image";
                }                   
                $rows["img_small"]=$img_small;      // end check img !
                $rows["our_price"]=number_format($rows["our_price"], 2, '.', ' ');
            $total+=$rows[our_price]*$v[qty];
            
            $cart[]=$rows+array("qty" => $v[qty], "subtotal" => number_format($rows[our_price]*$v[qty], 2, '.', ' '));
            
        }
        $render->assign("cart", $cart);
        $render->assign("total", number_format($total, 2, '.', ' '));
        $render->assign("total_n", $total);
        
        $clients = $db->getall("select client_id as id, client_name as name from clients where client_name != 'noone' and client_name != 'Administrator' order by client_name asc");
        $render->assign("clients", $clients);
        
        if (isset($_SESSION[error])) 
        {
            $render->assign("error", $_SESSION[error]);
            unset($_SESSION[error]);
        }
        if (isset($_SESSION[ok])) 
        {
            $render->assign("ok", $_SESSION[ok]);
            unset($_SESSION[ok]);
        }
        
        return "productlist.tpl.php";

    } /// renderProductList



// ----------------------------------------------------------------------------------
// --- [ Generate Product Edit page ] --------------------------------------------------
// ----------------------------------------------------------------------------------



};
?>